import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCDemo1 {
    public static void main(String[] args) throws SQLException {
        //实现控制台入
        Scanner in = new Scanner(System.in);
        System.out.println("请输入学生的学号：");
        int id = in.nextInt();
        System.out.println("请输入学生的姓名：");
        String name = in.next();

        //1.创建"数据源"
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java108?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //2.和数据库建立连接
        Connection connection = dataSource.getConnection();
        //3.构造sql语句
//        String sql = "insert into student values("+id+",'"+name+"')";
        String sql = "insert into student values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        //4.执行sql语句
        int n = statement.executeUpdate();//返回值是几行受到影响
        System.out.println("n=" + n);
        //5.释放必要的资源，关闭连接
        statement.close();
        connection.close();
    }
}
